package com.joeone.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.joeone.entity.mti.*;
import com.joeone.mapper.mti.PerformanceOverviewMapper;
import com.joeone.request.JoeoneRequest;
import com.joeone.service.PerformanceOverviewService;
import com.joeone.utils.DecimalUtil;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
* @author 郑伟杰
* 描述：业绩总览列表-查询方法
* 创建时间 2024/3/18 8:54
*/
@Service
@RequiredArgsConstructor
public class PerformanceOverviewServiceImpl implements PerformanceOverviewService {
    private final PerformanceOverviewMapper performanceOverviewMapper;
    /**
     * 功能：查询业绩总览第一列表
     */
    @Override
    public List<PerformanceOverviewOne> queryPerformanceOverviewOne(JoeoneRequest joeoneRequest) {
        List<PerformanceOverviewOne> performanceOverviewOneList = new ArrayList<>();
        JSONObject jsonObject = this.queryYjTotal(joeoneRequest);
        PerformanceOverviewOne performanceOverviewOne_1 = (PerformanceOverviewOne) jsonObject.get("ls");
        PerformanceOverviewOne performanceOverviewOne_2 = (PerformanceOverviewOne) jsonObject.get("hk");
        performanceOverviewOneList.add(performanceOverviewOne_1);
        performanceOverviewOneList.add(performanceOverviewOne_2);
        return performanceOverviewOneList;
    }
    /**
     * 功能：查询业绩总览第二列表
     */
    @Override
    public List<PerformanceOverviewTwo> queryPerformanceOverviewTwo(JoeoneRequest joeoneRequest) {
        List<PerformanceOverviewTwo> performanceOverviewTwoList = new ArrayList<>();
        List<JSONObject> jsonObjects = this.queryYjTotalGroupByStoreType(joeoneRequest);
        jsonObjects.stream().forEach(jsonObject -> {
            PerformanceOverviewTwo performanceOverviewTwo = (PerformanceOverviewTwo) jsonObject.get("ByStoreType");
            performanceOverviewTwoList.add(performanceOverviewTwo);
        });
        return performanceOverviewTwoList;
    }
    /**
     * 功能：查询业绩总览第三列表
     */
    @Override
    public List<PerformanceOverviewThree> queryPerformanceOverviewThree(JoeoneRequest joeoneRequest) {
        List<PerformanceOverviewThree> performanceOverviewThreeList = new ArrayList<>();
        List<JSONObject> jsonObjects = this.queryYjTotalGroupByComp(joeoneRequest);
        jsonObjects.stream().forEach(jsonObject -> {
            PerformanceOverviewThree performanceOverviewThree = (PerformanceOverviewThree) jsonObject.get("ByComp");
            performanceOverviewThreeList.add(performanceOverviewThree);
        });
        return performanceOverviewThreeList;
    }

    /**
     * 查询业绩总览
     * @param joeoneRequest
     * @return
     */
    public JSONObject queryYjTotal(JoeoneRequest joeoneRequest) {
        String dateType = joeoneRequest.getDateType();
        String period = joeoneRequest.getPeriod();
        String jyxz = joeoneRequest.getJyxz();
        List<String> comp = joeoneRequest.getComp();

        JSONObject result = new JSONObject();

        // 查询年度业绩目标
        List<JSONObject> yearTarget = performanceOverviewMapper.queryYearTarget(period, jyxz, comp, "", "", "");

        String periodTq = getTq(period);

        // 高效店业绩
        JSONObject saleQs = performanceOverviewMapper.querySale(dateType, period, periodTq, jyxz, comp, "", "1", "", "");
        JSONObject saleTqQs = performanceOverviewMapper.querySale(dateType, period, periodTq, jyxz, comp, "1", "1", "", ""); // 同期

        // 全国所有门店业绩
        JSONObject sale = performanceOverviewMapper.querySale(dateType, period, periodTq, jyxz, comp, "", "", "", "");
        JSONObject saleTq = performanceOverviewMapper.querySale(dateType, period, periodTq, jyxz, comp, "1", "", "", ""); // 同期

        BigDecimal mb = DecimalUtil.dafaultDecimal(saleQs,"mb");
        BigDecimal bq = DecimalUtil.dafaultDecimal(saleQs,"bq");
        BigDecimal tq = DecimalUtil.dafaultDecimal(saleTqQs,"bq");

        BigDecimal qgbq = DecimalUtil.dafaultDecimal(sale,"bq");
        BigDecimal qgtq = DecimalUtil.dafaultDecimal(saleTq,"bq");

        // 业绩总览的年度目标不需要过滤，直接汇总所以只有一条
        JSONObject ls = yearTarget.get(0);
        PerformanceOverviewOne performanceOverviewOne_1 = new PerformanceOverviewOne();
        performanceOverviewOne_1.setIndex("零售");
        if(null != ls){
            performanceOverviewOne_1.setAnnualChallengeGoals(ls.get("year_target") == null ? "/" : ls.get("year_target").toString());
        }else{
            performanceOverviewOne_1.setAnnualChallengeGoals(null);
        }
        performanceOverviewOne_1.setTarget(mb);
        performanceOverviewOne_1.setActual(bq);
        performanceOverviewOne_1.setRate(DecimalUtil.divideDecimal(bq,mb)==null?"/":DecimalUtil.divideDecimal(bq,mb).toString());
        performanceOverviewOne_1.setSynchronous(tq);
        performanceOverviewOne_1.setYearOnYear(DecimalUtil.divideDecimal(DecimalUtil.subtractDecimal(bq,tq),tq));
        performanceOverviewOne_1.setNationwide(qgbq);
        performanceOverviewOne_1.setNationwideRatio(DecimalUtil.divideDecimal(DecimalUtil.subtractDecimal(qgbq,qgtq),qgtq));
        performanceOverviewOne_1.setProportionHighEfficiencyStores(DecimalUtil.divideDecimal(bq,qgbq));

        // 高效店回款
        JSONObject saleHkQs = performanceOverviewMapper.querySaleHk(dateType, period, periodTq, jyxz, comp, "", "1");
        JSONObject saleHkTqQs = performanceOverviewMapper.querySaleHk(dateType, period, periodTq, jyxz, comp, "1", "1"); // 同期

        // 全国所有门店回款
        JSONObject saleHk = performanceOverviewMapper.querySaleHk(dateType, period, periodTq, jyxz, comp, "", "");
        JSONObject saleHkTq = performanceOverviewMapper.querySaleHk(dateType, period, periodTq, jyxz, comp, "1", ""); // 同期

        BigDecimal hkmb = DecimalUtil.dafaultDecimal(saleHkQs,"mb");
        BigDecimal hkbq = DecimalUtil.dafaultDecimal(saleHkQs,"bq");
        BigDecimal hktq = DecimalUtil.dafaultDecimal(saleHkTqQs,"bq");

        BigDecimal hkQgbq = DecimalUtil.dafaultDecimal(saleHk,"bq");
        BigDecimal hkQgtq = DecimalUtil.dafaultDecimal(saleHkTq,"bq");

        // 回款没有年度目标
        PerformanceOverviewOne performanceOverviewOne_2 = new PerformanceOverviewOne();
        performanceOverviewOne_2.setIndex("回款");
        performanceOverviewOne_2.setAnnualChallengeGoals("/");
        performanceOverviewOne_2.setTarget(hkmb);
        performanceOverviewOne_2.setActual(hkbq);
        performanceOverviewOne_2.setRate(DecimalUtil.divideDecimal(hkbq,hkmb)==null?"/": DecimalUtil.divideDecimal(hkbq,hkmb).toString());
        performanceOverviewOne_2.setSynchronous(hktq);
        performanceOverviewOne_2.setYearOnYear(DecimalUtil.divideDecimal(DecimalUtil.subtractDecimal(hkbq,hktq),hktq));
        performanceOverviewOne_2.setNationwide(hkQgbq);
        performanceOverviewOne_2.setNationwideRatio(DecimalUtil.divideDecimal(DecimalUtil.subtractDecimal(hkQgbq,hkQgtq),hkQgtq));
        performanceOverviewOne_2.setProportionHighEfficiencyStores(DecimalUtil.divideDecimal(bq,hkQgbq));

        result.put("ls", performanceOverviewOne_1);
        result.put("hk", performanceOverviewOne_2);
        // TODO result.put("dx", dx);

        return result;
    }

    /**
     * 查询业绩总览_按类型汇总
     * @param joeoneRequest
     * @return
     */
    public List<JSONObject> queryYjTotalGroupByStoreType(JoeoneRequest joeoneRequest) {
        String dateType = joeoneRequest.getDateType();
        String period = joeoneRequest.getPeriod();
        String jyxz = joeoneRequest.getJyxz();
        List<String> comp = joeoneRequest.getComp();
        String periodTq = getTq(period);
        // 查询业绩总览_按类型汇总
        List<JSONObject> yjByType = performanceOverviewMapper.queryYjTotalGroupByStoreType(dateType, period, periodTq, jyxz, comp, "");
        for (JSONObject tmp : yjByType) {
            BigDecimal mb = DecimalUtil.dafaultDecimal(tmp,"mb");
            BigDecimal bq = DecimalUtil.dafaultDecimal(tmp,"bq");
            PerformanceOverviewTwo performanceOverviewTwo = new PerformanceOverviewTwo();
            performanceOverviewTwo.setType(tmp.getString("TZMB"));
            performanceOverviewTwo.setAnnualChallengeGoals(tmp.getString("year_mb"));
            performanceOverviewTwo.setActualStores(tmp.getString("count"));
            performanceOverviewTwo.setTarget(mb);
            performanceOverviewTwo.setRetail(bq);
            performanceOverviewTwo.setRate(DecimalUtil.divideDecimal(bq,mb)==null?"/": DecimalUtil.divideDecimal(bq,mb).toString());
            performanceOverviewTwo.setDifference(tmp.getString("cy"));
            tmp.put("ByStoreType",performanceOverviewTwo);
        }
        return yjByType;
    }

    /**
     * 查询业绩总览_按分公司汇总
     * @param joeoneRequest
     * @return
     */
    public List<JSONObject> queryYjTotalGroupByComp(JoeoneRequest joeoneRequest) {
        String dateType = joeoneRequest.getDateType();
        String period = joeoneRequest.getPeriod();
        String jyxz = joeoneRequest.getJyxz();
        List<String> comp = joeoneRequest.getComp();
        String periodTq = getTq(period);
        // 查询业绩总览_按分公司汇总
        List<JSONObject> yjByComp = performanceOverviewMapper.queryYjTotalGroupByComp(dateType, period, periodTq, jyxz, comp, "");
        for (JSONObject tmp : yjByComp) {
            BigDecimal mb = DecimalUtil.dafaultDecimal(tmp,"mb");
            BigDecimal bq = DecimalUtil.dafaultDecimal(tmp,"bq");
            PerformanceOverviewThree performanceOverviewThree = new PerformanceOverviewThree();
            performanceOverviewThree.setCompany(tmp.getString("FGS"));
            performanceOverviewThree.setAnnualChallengeGoals(tmp.getString("year_mb"));
            performanceOverviewThree.setActualStores(tmp.getString("count"));
            performanceOverviewThree.setTarget(tmp.getString("mb"));
            performanceOverviewThree.setRetail(tmp.getString("bq"));
            performanceOverviewThree.setRate(DecimalUtil.divideDecimal(bq,mb)==null?"/": DecimalUtil.divideDecimal(bq,mb).toString());
            performanceOverviewThree.setDifference(tmp.getString("cy"));
            tmp.put("ByComp", performanceOverviewThree);
        }

        return yjByComp;
    }

    /**
     * 查询零售指标
     * @param joeoneRequest
     * @return
     */
    public Retail querySaleZhibiao(JoeoneRequest joeoneRequest) {
        String dateType = joeoneRequest.getDateType();
        String period = joeoneRequest.getPeriod();
        String jyxz = joeoneRequest.getJyxz();
        List<String> comp = joeoneRequest.getComp();
        String periodTq = getTq(period);

        // 零售指标（筛选渠道业态不包含其他）
        JSONObject qdytWhithoutQt = performanceOverviewMapper.querySale(dateType, period, periodTq, jyxz, comp, "", "1", "1", "");
        JSONObject qdytWhithoutQtTq = performanceOverviewMapper.querySale(dateType, period, periodTq, jyxz, comp, "1", "1", "1", "");
        List<JSONObject> zlList = performanceOverviewMapper.querySaleZl(dateType, period, periodTq, jyxz, comp, "1");

        // 零售指标（筛选渠道业态不包含其他）全国
        JSONObject qdytWhithoutQtQg = performanceOverviewMapper.querySale(dateType, period, periodTq, jyxz, comp, "", "", "1", "");
        JSONObject qdytWhithoutQtQgTq = performanceOverviewMapper.querySale(dateType, period, periodTq, jyxz, comp, "1", "", "1", "");
        List<JSONObject> zlListQg = performanceOverviewMapper.querySaleZl(dateType, period, periodTq, jyxz, comp, "");

        // 零售指标（渠道业态只包含其他）
        JSONObject qdytOnlyQt = performanceOverviewMapper.querySale(dateType, period, periodTq, jyxz, comp, "", "1", "1", "1");
        JSONObject qdytOnlyQtTq = performanceOverviewMapper.querySale(dateType, period, periodTq, jyxz, comp, "1", "1", "1", "1");
        Retail retail = new Retail();
        List<RetailOne> retailOneList = new ArrayList<>();
        List<RetailTwo> retailTwoList = new ArrayList<>();
        // 1.2零售第一个表格，不筛选包括其他
        // 客单价
        BigDecimal kdjWhithOutQtBq = DecimalUtil.dafaultDecimal(qdytWhithoutQt,"kdj");
        BigDecimal kdjWhithOutQtTq = DecimalUtil.dafaultDecimal(qdytWhithoutQtTq,"kdj");
        BigDecimal kdjWhithOutQtQgBq = DecimalUtil.dafaultDecimal(qdytWhithoutQtQg,"kdj");
        BigDecimal kdjWhithOutQtQgTq = DecimalUtil.dafaultDecimal(qdytWhithoutQtQgTq,"kdj");

        RetailOne retailOne_kdj = new RetailOne();
        retailOne_kdj.setIndex("客单价");
        retailOne_kdj.setActual(kdjWhithOutQtBq);
        retailOne_kdj.setSynchronous(kdjWhithOutQtTq);
        retailOne_kdj.setYearOnYear(DecimalUtil.divideDecimal(DecimalUtil.subtractDecimal(kdjWhithOutQtBq,kdjWhithOutQtTq),kdjWhithOutQtTq));
        retailOne_kdj.setNationwide(kdjWhithOutQtQgBq);
        retailOne_kdj.setNationwideRatio(DecimalUtil.divideDecimal(DecimalUtil.subtractDecimal(kdjWhithOutQtQgBq,kdjWhithOutQtQgTq),kdjWhithOutQtQgTq));
        retailOneList.add(retailOne_kdj);

        // 连带率
        BigDecimal ldlWhithOutQtBq = DecimalUtil.dafaultDecimal(qdytWhithoutQt,"ldl");
        BigDecimal ldlWhithOutQtTq = DecimalUtil.dafaultDecimal(qdytWhithoutQtTq,"ldl");
        BigDecimal ldlWhithOutQtQgBq = DecimalUtil.dafaultDecimal(qdytWhithoutQtQg,"ldl");
        BigDecimal ldlWhithOutQtQgTq = DecimalUtil.dafaultDecimal(qdytWhithoutQtQgTq,"ldl");

        RetailOne retailOne_ldl = new RetailOne();
        retailOne_ldl.setIndex("连带率");
        retailOne_ldl.setActual(ldlWhithOutQtBq);
        retailOne_ldl.setSynchronous(ldlWhithOutQtTq);
        retailOne_ldl.setYearOnYear(DecimalUtil.subtractDecimal(ldlWhithOutQtBq,ldlWhithOutQtTq));
        retailOne_ldl.setNationwide(ldlWhithOutQtQgBq);
        retailOne_ldl.setNationwideRatio(DecimalUtil.subtractDecimal(ldlWhithOutQtQgBq,ldlWhithOutQtQgTq));
        retailOneList.add(retailOne_ldl);

        // 件单价
        BigDecimal jdjWhithOutQtBq = DecimalUtil.dafaultDecimal(qdytWhithoutQt,"jdj");
        BigDecimal jdjWhithOutQtTq = DecimalUtil.dafaultDecimal(qdytWhithoutQtTq,"jdj");
        BigDecimal jdjWhithOutQtQgBq = DecimalUtil.dafaultDecimal(qdytWhithoutQtQg,"jdj");
        BigDecimal jdjWhithOutQtQgTq = DecimalUtil.dafaultDecimal(qdytWhithoutQtQgTq,"jdj");

        RetailOne retailOne_jdj = new RetailOne();
        retailOne_jdj.setIndex("件单价");
        retailOne_jdj.setActual(jdjWhithOutQtBq);
        retailOne_jdj.setSynchronous(jdjWhithOutQtTq);
        retailOne_jdj.setYearOnYear(DecimalUtil.divideDecimal(DecimalUtil.subtractDecimal(jdjWhithOutQtBq,jdjWhithOutQtTq),jdjWhithOutQtTq));
        retailOne_jdj.setNationwide(jdjWhithOutQtQgBq);
        retailOne_jdj.setNationwideRatio(DecimalUtil.divideDecimal(DecimalUtil.subtractDecimal(jdjWhithOutQtQgBq,jdjWhithOutQtQgTq),jdjWhithOutQtQgTq));
        retailOneList.add(retailOne_jdj);

        // 成交单数
        BigDecimal cjdsWhithOutQtBq = DecimalUtil.dafaultDecimal(qdytWhithoutQt,"cjds");
        BigDecimal cjdsWhithOutQtTq = DecimalUtil.dafaultDecimal(qdytWhithoutQtTq,"cjds");
        BigDecimal cjdsWhithOutQtQgBq = DecimalUtil.dafaultDecimal(qdytWhithoutQtQg,"cjds");
        BigDecimal cjdsWhithOutQtQgTq = DecimalUtil.dafaultDecimal(qdytWhithoutQtQgTq,"cjds");
        // 成交单数
        RetailOne retailOne_cjds = new RetailOne();
        retailOne_cjds.setIndex("成交单数");
        retailOne_cjds.setActual(cjdsWhithOutQtBq);
        retailOne_cjds.setSynchronous(cjdsWhithOutQtTq);
        retailOne_cjds.setYearOnYear(DecimalUtil.divideDecimal(DecimalUtil.subtractDecimal(cjdsWhithOutQtBq,cjdsWhithOutQtTq),cjdsWhithOutQtTq));
        retailOne_cjds.setNationwide(cjdsWhithOutQtQgBq);
        retailOne_cjds.setNationwideRatio(DecimalUtil.divideDecimal(DecimalUtil.subtractDecimal(cjdsWhithOutQtQgBq,cjdsWhithOutQtQgTq),cjdsWhithOutQtQgTq));
        retailOneList.add(retailOne_cjds);

        Map<String, JSONObject> qgzl = zlListQg.stream().collect(Collectors.toMap(x -> x.getString("XJP"), x -> x));
        for (JSONObject tmp : zlList) {
            String zb = tmp.getString("XJP");
            BigDecimal zl = DecimalUtil.dafaultDecimal(tmp,"zl");
            BigDecimal zl_tq = DecimalUtil.dafaultDecimal(tmp,"zl_tq");
            JSONObject qg = qgzl.get(zb);
            BigDecimal zlqg = DecimalUtil.dafaultDecimal(qg,"zl");
            BigDecimal zlqg_tq = DecimalUtil.dafaultDecimal(qg,"zl_tq");

            RetailOne retailOne_xjp = new RetailOne();
            retailOne_xjp.setIndex(zb);
            retailOne_xjp.setActual(zl);
            retailOne_xjp.setSynchronous(zl_tq);
            retailOne_xjp.setYearOnYear(DecimalUtil.subtractDecimal(zl,zl_tq));
            retailOne_xjp.setNationwide(zlqg);
            retailOne_xjp.setNationwideRatio(DecimalUtil.subtractDecimal(zlqg,zlqg_tq));
            retailOneList.add(retailOne_xjp);
        }
        retail.setRetailOneList(retailOneList);


        // 1.2零售第二个表格，只包括其他
        List<JSONObject> table2 = new ArrayList<>();
        // 客单价
        BigDecimal kdjOnlyQtBq = DecimalUtil.dafaultDecimal(qdytOnlyQt,"kdj");
        BigDecimal kdjOnlyQtTq = DecimalUtil.dafaultDecimal(qdytOnlyQtTq,"kdj");

        RetailTwo retailTwo_kdj = new RetailTwo();
        retailTwo_kdj.setIndex("客单价");// 指标
        retailTwo_kdj.setActual(kdjOnlyQtBq);// 实际
        retailTwo_kdj.setSynchronous(kdjOnlyQtTq);// 同期
        retailTwo_kdj.setYearOnYear(DecimalUtil.divideDecimal(DecimalUtil.subtractDecimal(kdjOnlyQtBq,kdjOnlyQtTq),kdjOnlyQtTq));// 同比
        retailTwoList.add(retailTwo_kdj);

        // 连带率
        BigDecimal ldlOnlyQtBq = DecimalUtil.dafaultDecimal(qdytOnlyQt,"ldl");
        BigDecimal ldlOnlyQtTq = DecimalUtil.dafaultDecimal(qdytOnlyQtTq,"ldl");

        RetailTwo retailTwo_ldl = new RetailTwo();
        retailTwo_ldl.setIndex("连带率");// 指标
        retailTwo_ldl.setActual(ldlOnlyQtBq); // 实际
        retailTwo_ldl.setSynchronous(ldlOnlyQtTq);// 同期
        retailTwo_ldl.setYearOnYear(DecimalUtil.subtractDecimal(ldlOnlyQtBq,ldlOnlyQtTq));// 同比
        retailTwoList.add(retailTwo_ldl);
        // 件单价
        BigDecimal jdjOnlyQtBq = DecimalUtil.dafaultDecimal(qdytOnlyQt,"jdj");
        BigDecimal jdjOnlyQtTq = DecimalUtil.dafaultDecimal(qdytOnlyQtTq,"jdj");

        RetailTwo retailTwo_zdj = new RetailTwo();
        retailTwo_zdj.setIndex("件单价");// 指标
        retailTwo_zdj.setActual(jdjOnlyQtBq); // 实际
        retailTwo_zdj.setSynchronous(jdjOnlyQtTq);// 同期
        retailTwo_zdj.setYearOnYear(DecimalUtil.divideDecimal(DecimalUtil.subtractDecimal(jdjOnlyQtBq,jdjOnlyQtTq),jdjOnlyQtTq));// 同比
        retailTwoList.add(retailTwo_zdj);

        // 成交单数
        BigDecimal cjdsOnlyQtBq = DecimalUtil.dafaultDecimal(qdytOnlyQt,"cjds");
        BigDecimal cjdsOnlyQtTq = DecimalUtil.dafaultDecimal(qdytOnlyQtTq,"cjds");
        RetailTwo retailTwo_cjds = new RetailTwo();
        retailTwo_cjds.setIndex("成交单数");// 指标
        retailTwo_cjds.setActual(cjdsOnlyQtBq); // 实际
        retailTwo_cjds.setSynchronous(cjdsOnlyQtTq);// 同期
        retailTwo_cjds.setYearOnYear(DecimalUtil.divideDecimal(DecimalUtil.subtractDecimal(cjdsOnlyQtBq,cjdsOnlyQtTq),cjdsOnlyQtTq));// 同比
        retailTwoList.add(retailTwo_cjds);
        retail.setRetailTwoList(retailTwoList);

        return retail;
    }

    /**
     * 查询业绩总览_按渠道业态汇总
     * @param joeoneRequest
     * @return
     */
    public ChannelAnalysis queryYjTotalGroupByQdyt(JoeoneRequest joeoneRequest) {
        String dateType = joeoneRequest.getDateType();
        String period = joeoneRequest.getPeriod();
        String jyxz = joeoneRequest.getJyxz();
        List<String> comp = joeoneRequest.getComp();
        String periodTq = getTq(period);
        String periodHb = getHbDate(period, dateType);

        // 本期
        List<JSONObject> qdyt = performanceOverviewMapper.queryYjTotalGroupByQdyt(dateType, period, periodTq, jyxz, comp, "", "1");
        List<JSONObject> qdytQg = performanceOverviewMapper.queryYjTotalGroupByQdyt(dateType, period, periodTq, jyxz, comp, "", "0");
        Map<String, JSONObject> qdytQgCache = qdytQg.stream().collect(Collectors.toMap(x -> x.getString("QDYT"), x -> x));

        // 环比时间数据
        List<JSONObject> qdytHb = new ArrayList<>();
        if ("周".equals(dateType) || "月".equals(dateType)) {
            qdytHb = performanceOverviewMapper.queryYjTotalGroupByQdyt(dateType, periodHb, periodTq, jyxz, comp, "", "1");
        }
        Map<String, JSONObject> qdytHbCache = qdytHb.stream().collect(Collectors.toMap(x -> x.getString("QDYT"), x -> x));

        // 同期
        List<JSONObject> qdytTq = performanceOverviewMapper.queryYjTotalGroupByQdyt(dateType, period, periodTq, jyxz, comp, "1", "1");
        List<JSONObject> qdytTqQg = performanceOverviewMapper.queryYjTotalGroupByQdyt(dateType, period, periodTq, jyxz, comp, "1", "0");
        Map<String, JSONObject> qdytTqCache = qdytTq.stream().collect(Collectors.toMap(x -> x.getString("QDYT"), x -> x));
        Map<String, JSONObject> qdytTqQgCache = qdytTqQg.stream().collect(Collectors.toMap(x -> x.getString("QDYT"), x -> x));

        // 回款
        List<JSONObject> saleHkQs = performanceOverviewMapper.querySaleHkGroupByQdyt(dateType, period, periodTq, jyxz, comp, "", "1");
        Map<String, JSONObject> saleHkQsCache = saleHkQs.stream().collect(Collectors.toMap(x -> x.getString("QDYT"), x -> x));

        // 零售折率
        List<JSONObject> zlQs = performanceOverviewMapper.querySaleZlGroupByQdyt(dateType, period, periodTq, jyxz, comp, "1");
        Map<String, JSONObject> zlQsCache = zlQs.stream().collect(Collectors.toMap(x -> (x.getString("QDYT") + "_" + x.getString("XJP")), x -> x));

        List<JSONObject> zlHbQs = performanceOverviewMapper.querySaleZlGroupByQdyt(dateType, periodHb, periodTq, jyxz, comp, "1");
        Map<String, JSONObject> zlHbQsCache = zlHbQs.stream().collect(Collectors.toMap(x -> (x.getString("QDYT") + "_" + x.getString("XJP")), x -> x));
        ChannelAnalysis channelAnalysis = new ChannelAnalysis();
        List<ChannelAnalysisOne> channelAnalysisOneList = new ArrayList<>();
        List<ChannelAnalysisTwo> channelAnalysisTwoList = new ArrayList<>();
        for (JSONObject tmp : qdyt) {
            String lb = tmp.getString("QDYT");// 类别
            JSONObject tmpQg = qdytQgCache.get(lb);
            JSONObject tmpTq = qdytTqCache.get(lb);
            JSONObject tmpTqQg = qdytTqQgCache.get(lb);

            BigDecimal count = DecimalUtil.dafaultDecimal(tmp,"count");// 高效门店数量
            BigDecimal countQg = DecimalUtil.dafaultDecimal(tmpQg,"count");// 全国门店数量

            BigDecimal bq = DecimalUtil.dafaultDecimal(tmp,"bq");// 高效门店零售本期
            BigDecimal bqQg = DecimalUtil.dafaultDecimal(tmpQg,"bq");// 全国门店零售本期

            BigDecimal tq = DecimalUtil.dafaultDecimal(tmpTq,"bq");// 高效门店零售同期
            BigDecimal tqQg = DecimalUtil.dafaultDecimal(tmpTqQg,"bq");// 全国门店零售同期

            // 按照表格顺序，看这里即可
            ChannelAnalysisOne channelAnalysisOne = new ChannelAnalysisOne();
            channelAnalysisOne.setType(tmp.getString("QDYT"));// 类别
            channelAnalysisOne.setAnnualChallengeGoals(tmp.getString("year_mb")); // 年度挑战目标
            channelAnalysisOne.setPercentageStores(DecimalUtil.divideDecimal(count,countQg));// 门店数量占比
            channelAnalysisOne.setPercentageRetailAmount(DecimalUtil.divideDecimal(bq,bqQg));// 零售金额占比
            channelAnalysisOne.setTarget(DecimalUtil.dafaultDecimal(tmp,"mb"));// 目标
            channelAnalysisOne.setActual(DecimalUtil.dafaultDecimal(tmp,"bq"));// 实际
            channelAnalysisOne.setRate(DecimalUtil.divideDecimal(bq,DecimalUtil.dafaultDecimal(tmp,"mb")));// 达成率
            channelAnalysisOne.setSynchronous(tq);// 同期
            channelAnalysisOne.setYearOnYear(DecimalUtil.divideDecimal(DecimalUtil.subtractDecimal(bq,tq),tq)); // 同比
            channelAnalysisOne.setNationwideRatio(DecimalUtil.divideDecimal(DecimalUtil.subtractDecimal(bqQg,tqQg),tqQg)); // 全国同比
            // 环比
            if ("周".equals(dateType) || "月".equals(dateType)) {
                JSONObject tmpHb = qdytHbCache.get(lb);
                BigDecimal bqHb = DecimalUtil.dafaultDecimal(tmpHb,"bq");// 高效门店零售环比时间
                channelAnalysisOne.setChain(DecimalUtil.divideDecimal(DecimalUtil.subtractDecimal(bq,bqHb),bqHb)); // 环比
            }
            //填充完第一列表数据
            channelAnalysisOneList.add(channelAnalysisOne);
            channelAnalysis.setChannelAnalysisOneList(channelAnalysisOneList);
            //填充完第一列表数据

            JSONObject tmpHk = saleHkQsCache.get(lb);
            BigDecimal hk = DecimalUtil.dafaultDecimal(tmpHk,"bq");// 高效门店回款本期
            if ("月".equals(dateType) || "年".equals(dateType)) {
                channelAnalysisOne.setChannelCostRatio(DecimalUtil.divideDecimal(DecimalUtil.subtractDecimal(bq,hk),bq)); // 渠道成本率
            }
            ChannelAnalysisTwo channelAnalysisTwo_kdj = new ChannelAnalysisTwo();// 客单价
            ChannelAnalysisTwo channelAnalysisTwo_ldl = new ChannelAnalysisTwo();// 连带率
            ChannelAnalysisTwo channelAnalysisTwo_jdj = new ChannelAnalysisTwo();// 件单价
            ChannelAnalysisTwo channelAnalysisTwo_cjds = new ChannelAnalysisTwo();// 成交单数
            ChannelAnalysisTwo channelAnalysisTwo_xp = new ChannelAnalysisTwo();// 新品零售折率
            ChannelAnalysisTwo channelAnalysisTwo_jp = new ChannelAnalysisTwo();// 旧品零售折率

            JSONObject tmpZlQsXp = zlQsCache.get(lb + "_新品");
            JSONObject tmpZlQsJp = zlQsCache.get(lb + "_旧品");

            // 本期=实际
            BigDecimal kdj = DecimalUtil.dafaultDecimal(tmp,"kdj");// 客单价
            BigDecimal ldl = DecimalUtil.dafaultDecimal(tmp,"ldl");// 连带率
            BigDecimal jdj = DecimalUtil.dafaultDecimal(tmp,"jdj");// 件单价
            BigDecimal cjds = DecimalUtil.dafaultDecimal(tmp,"cjds");// 成交单数
            BigDecimal xp = DecimalUtil.dafaultDecimal(tmpZlQsXp,"zl");// 新品零售折率
            BigDecimal jp = DecimalUtil.dafaultDecimal(tmpZlQsJp,"zl");// 旧品零售折率

            channelAnalysisTwo_kdj.setType(lb);
            channelAnalysisTwo_ldl.setType(lb);
            channelAnalysisTwo_jdj.setType(lb);
            channelAnalysisTwo_cjds.setType(lb);
            channelAnalysisTwo_xp.setType(lb);
            channelAnalysisTwo_jp.setType(lb);

            channelAnalysisTwo_kdj.setKpiMetrics("客单价");
            channelAnalysisTwo_ldl.setKpiMetrics("连带率");
            channelAnalysisTwo_jdj.setKpiMetrics("件单价");
            channelAnalysisTwo_cjds.setKpiMetrics("成交单数");
            channelAnalysisTwo_xp.setKpiMetrics("新品零售折率");
            channelAnalysisTwo_jp.setKpiMetrics("旧品零售折率");

            channelAnalysisTwo_kdj.setActual(kdj);
            channelAnalysisTwo_ldl.setActual(ldl);
            channelAnalysisTwo_jdj.setActual(jdj);
            channelAnalysisTwo_cjds.setActual(kdj);
            channelAnalysisTwo_xp.setActual(xp);
            channelAnalysisTwo_jp.setActual(jp);

            // 同期
            BigDecimal kdjTq = DecimalUtil.dafaultDecimal(tmpTq,"kdj");// 客单价
            BigDecimal ldlTq = DecimalUtil.dafaultDecimal(tmpTq,"ldl");// 连带率
            BigDecimal jdjTq = DecimalUtil.dafaultDecimal(tmpTq,"jdj");// 件单价
            BigDecimal cjdsTq = DecimalUtil.dafaultDecimal(tmpTq,"cjds");// 成交单数
            BigDecimal xpTq = DecimalUtil.dafaultDecimal(tmpZlQsXp,"zl_tq");// 新品零售折率
            BigDecimal jpTq = DecimalUtil.dafaultDecimal(tmpZlQsJp,"zl_tq");// 旧品零售折率

            channelAnalysisTwo_kdj.setSynchronous(kdjTq);//同期
            channelAnalysisTwo_ldl.setSynchronous(ldlTq);
            channelAnalysisTwo_jdj.setSynchronous(jdjTq);
            channelAnalysisTwo_cjds.setSynchronous(cjdsTq);
            channelAnalysisTwo_xp.setSynchronous(xpTq);
            channelAnalysisTwo_jp.setSynchronous(jpTq);

            channelAnalysisTwo_kdj.setYearOnYear(DecimalUtil.divideDecimal(DecimalUtil.subtractDecimal(kdj,kdjTq),kdjTq));//同比
            channelAnalysisTwo_ldl.setYearOnYear(DecimalUtil.subtractDecimal(ldl,ldlTq));
            channelAnalysisTwo_jdj.setYearOnYear(DecimalUtil.divideDecimal(DecimalUtil.subtractDecimal(jdj,jdjTq),jdjTq));//同比
            channelAnalysisTwo_cjds.setYearOnYear(DecimalUtil.divideDecimal(DecimalUtil.subtractDecimal(cjds,cjdsTq),cjdsTq));
            channelAnalysisTwo_xp.setYearOnYear(DecimalUtil.subtractDecimal(xp,xpTq));
            channelAnalysisTwo_jp.setYearOnYear(DecimalUtil.subtractDecimal(jp,jpTq));

            // 环比
            if ("周".equals(dateType) || "月".equals(dateType)) {
                JSONObject tmpHb = qdytHbCache.get(lb);
                JSONObject tmpZlHbQsXp = zlHbQsCache.get(lb + "_新品");
                JSONObject tmpZlHbQsJp = zlHbQsCache.get(lb + "_旧品");

                BigDecimal kdjHb = DecimalUtil.dafaultDecimal(tmpHb,"kdj");// 客单价
                BigDecimal ldlHb = DecimalUtil.dafaultDecimal(tmpHb,"ldl");// 连带率
                BigDecimal jdjHb = DecimalUtil.dafaultDecimal(tmpHb,"jdj");// 件单价
                BigDecimal cjdsHb = DecimalUtil.dafaultDecimal(tmpHb,"cjds");// 成交单数
                BigDecimal xpHb = DecimalUtil.dafaultDecimal(tmpZlHbQsXp,"zl");// 新品零售折率
                BigDecimal jpHb = DecimalUtil.dafaultDecimal(tmpZlHbQsJp,"zl");// 旧品零售折率

                channelAnalysisTwo_kdj.setChain(DecimalUtil.divideDecimal(DecimalUtil.subtractDecimal(kdj,kdjHb),kdjHb));//环比
                channelAnalysisTwo_ldl.setChain(DecimalUtil.subtractDecimal(ldl,ldlHb));
                channelAnalysisTwo_jdj.setChain(DecimalUtil.divideDecimal(DecimalUtil.subtractDecimal(jdj,jdjHb),jdjHb));
                channelAnalysisTwo_cjds.setChain(DecimalUtil.divideDecimal(DecimalUtil.subtractDecimal(cjds,cjdsHb),cjdsHb));
                channelAnalysisTwo_xp.setChain(DecimalUtil.subtractDecimal(xp,xpHb));
                channelAnalysisTwo_jp.setChain(DecimalUtil.subtractDecimal(jp,jpHb));
            }
            //填充完第二列表数据
            channelAnalysisTwoList.add(channelAnalysisTwo_kdj);
            channelAnalysisTwoList.add(channelAnalysisTwo_ldl);
            channelAnalysisTwoList.add(channelAnalysisTwo_jdj);
            channelAnalysisTwoList.add(channelAnalysisTwo_cjds);
            channelAnalysisTwoList.add(channelAnalysisTwo_xp);
            channelAnalysisTwoList.add(channelAnalysisTwo_jp);
            channelAnalysis.setChannelAnalysisTwoList(channelAnalysisTwoList);
            //填充完第二列表数据
        }

        return channelAnalysis;
//        return qdyt;
    }

    /**
     * 查询业绩总览_按大类销售汇总
     * @param joeoneRequest
     * @return
     */
    public Map<String, List<CategorySalesaAnalysis>> queryYjTotalGroupByDl(JoeoneRequest joeoneRequest) {
        String dateType = joeoneRequest.getDateType();
        String period = joeoneRequest.getPeriod();
        String jyxz = joeoneRequest.getJyxz();
        List<String> comp = joeoneRequest.getComp();

        List<JSONObject> dlList = performanceOverviewMapper.queryYjTotalGroupByDl(dateType, period, jyxz, comp);
        Map<String, JSONObject> dlListCache = dlList.stream().collect(Collectors.toMap(x -> x.getString("dl") + "_" + x.getString("xjp"), x -> x));
        //大类适销率计算时，取数
        Map<String, JSONObject> dlMarketabilityListCache = null;
        if(StringUtils.isNotEmpty(jyxz)&&"直营".equals(jyxz)){
            List<JSONObject> dlMarketabilityList = performanceOverviewMapper.queryMarketabilityByDl(dateType, period,comp);
            dlMarketabilityListCache = dlMarketabilityList.stream().collect(Collectors.toMap(x -> x.getString("dl"), x -> x));
        }

        List<String> dls = dlList.stream().map(x -> x.getString("dl")).distinct().collect(Collectors.toList());
        double amtXpSum = dlList.stream().filter(x -> "新品".equals(x.getString("xjp"))).mapToDouble(x -> x.getDouble("amt")).sum();
        double amtJpSum = dlList.stream().filter(x -> "旧品".equals(x.getString("xjp"))).mapToDouble(x -> x.getDouble("amt")).sum();

        Map<String, List<CategorySalesaAnalysis>> result = new HashMap<>();
        result.put("xp", new ArrayList<>());
        result.put("jp", new ArrayList<>());
        result.put("all", new ArrayList<>());

        for (String dl : dls) {
            JSONObject xp = dlListCache.get(dl + "_新品");
            JSONObject jp = dlListCache.get(dl + "_旧品");
            JSONObject sxl = dlMarketabilityListCache==null?null:dlMarketabilityListCache.get(dl);//适销率相关数据

            CategorySalesaAnalysis categorySalesaAnalysis_all = new CategorySalesaAnalysis();
            CategorySalesaAnalysis categorySalesaAnalysis_xp = new CategorySalesaAnalysis();
            CategorySalesaAnalysis categorySalesaAnalysis_jp = new CategorySalesaAnalysis();
            categorySalesaAnalysis_all.setType(dl);
            categorySalesaAnalysis_xp.setType(dl);
            categorySalesaAnalysis_jp.setType(dl);
            // dl  大类
            // amt  金额
            BigDecimal xpAmt = DecimalUtil.dafaultDecimal(xp,"amt");
            BigDecimal xpAmtTq = DecimalUtil.dafaultDecimal(xp,"amt_tq");
            BigDecimal jpAmt = DecimalUtil.dafaultDecimal(jp,"amt");
            BigDecimal jpAmtTq = DecimalUtil.dafaultDecimal(jp,"amt_tq");
            BigDecimal allAmt = DecimalUtil.addDecimal(xpAmt,jpAmt);
            BigDecimal allAmtTq = DecimalUtil.addDecimal(xpAmtTq,jpAmtTq);
            categorySalesaAnalysis_all.setAmount(allAmt);
            categorySalesaAnalysis_xp.setAmount(xpAmt);
            categorySalesaAnalysis_jp.setAmount(jpAmt);
            // 金额占比
            categorySalesaAnalysis_all.setPercentageAmount(DecimalUtil.divideDecimal(allAmt,new BigDecimal(amtXpSum + amtJpSum)));// 金额占比
            categorySalesaAnalysis_xp.setPercentageAmount(DecimalUtil.divideDecimal(xpAmt,new BigDecimal(amtXpSum)));
            categorySalesaAnalysis_jp.setPercentageAmount(DecimalUtil.divideDecimal(jpAmt,new BigDecimal(amtJpSum)));
            // 金额同比
            categorySalesaAnalysis_all.setYearOnYearAmount(DecimalUtil.divideDecimal(DecimalUtil.subtractDecimal(allAmt,allAmtTq),allAmtTq));// 金额同比
            categorySalesaAnalysis_xp.setYearOnYearAmount(DecimalUtil.divideDecimal(DecimalUtil.subtractDecimal(xpAmt,xpAmtTq),xpAmtTq));
            categorySalesaAnalysis_jp.setYearOnYearAmount(DecimalUtil.divideDecimal(DecimalUtil.subtractDecimal(jpAmt,jpAmtTq),jpAmtTq));
            // qty 数量
            BigDecimal xpQty =  DecimalUtil.dafaultDecimal(xp,"qty");
            BigDecimal xpQtyTq = DecimalUtil.dafaultDecimal(xp,"qty_tq");
            BigDecimal jpQty = DecimalUtil.dafaultDecimal(jp,"qty");
            BigDecimal jpQtyTq = DecimalUtil.dafaultDecimal(jp,"qty_tq");
            BigDecimal allQty = DecimalUtil.addDecimal(xpQty,jpQty);
            BigDecimal allQtyTq = DecimalUtil.addDecimal(xpQtyTq,jpQtyTq);

            categorySalesaAnalysis_all.setNum(allQty);//数量
            categorySalesaAnalysis_xp.setNum(xpQty);
            categorySalesaAnalysis_jp.setNum(jpQty);

            // 数量同比
            categorySalesaAnalysis_all.setYearOnYearAmountNum(DecimalUtil.divideDecimal(DecimalUtil.subtractDecimal(allQty,allQtyTq),allQtyTq));// 数量同比
            categorySalesaAnalysis_xp.setYearOnYearAmountNum(DecimalUtil.divideDecimal(DecimalUtil.subtractDecimal(xpQty,xpQtyTq),xpQtyTq));
            categorySalesaAnalysis_jp.setYearOnYearAmountNum(DecimalUtil.divideDecimal(DecimalUtil.subtractDecimal(jpQty,jpQtyTq),jpQtyTq));
            //新品-适销率  直营适销率=零售/(零售+库存)
            BigDecimal ls_qty = DecimalUtil.dafaultDecimal(sxl,"ls_qty");//零售数量
            BigDecimal kc_qty = DecimalUtil.dafaultDecimal(sxl,"kc_qty");//库存数量
            BigDecimal xp_sxl = DecimalUtil.divideDecimal(ls_qty, DecimalUtil.addDecimal(ls_qty, kc_qty));
            categorySalesaAnalysis_xp.setMarketability(xp_sxl);
            // zl 零售折率
            BigDecimal xpZl = DecimalUtil.dafaultDecimal(xp,"zl");
            BigDecimal xpZlTq = DecimalUtil.dafaultDecimal(xp,"zl_tq");
            BigDecimal jpZl = DecimalUtil.dafaultDecimal(jp,"zl");
            BigDecimal jpZlTq = DecimalUtil.dafaultDecimal(jp,"zl_tq");

            BigDecimal allTag = DecimalUtil.addDecimal(DecimalUtil.dafaultDecimal(xp,"tag"),DecimalUtil.dafaultDecimal(jp,"tag"));
            BigDecimal allTagTq = DecimalUtil.addDecimal(DecimalUtil.dafaultDecimal(xp,"tag_tq"),DecimalUtil.dafaultDecimal(jp,"tag_tq"));
            BigDecimal allZl = DecimalUtil.divideDecimal(allAmt,allTag);
            BigDecimal allZlTq = DecimalUtil.divideDecimal(allAmtTq,allTagTq);

            categorySalesaAnalysis_all.setRetailDiscount(allZl);//零售折率
            categorySalesaAnalysis_xp.setRetailDiscount(xpZl);
            categorySalesaAnalysis_jp.setRetailDiscount(jpZl);

            categorySalesaAnalysis_all.setYearOnYearRetailDiscount(DecimalUtil.subtractDecimal(allZl,allZlTq));//零售折率同比
            categorySalesaAnalysis_xp.setYearOnYearRetailDiscount(DecimalUtil.subtractDecimal(xpZl,xpZlTq));
            categorySalesaAnalysis_xp.setYearOnYearRetailDiscount(DecimalUtil.subtractDecimal(jpZl,jpZlTq));

            result.get("xp").add(categorySalesaAnalysis_xp);
            result.get("jp").add(categorySalesaAnalysis_jp);
            result.get("all").add(categorySalesaAnalysis_all);
        }

        return result;
    }

    @Override
    public List<String> queryFgs(String userId) {
        return performanceOverviewMapper.queryFgs(userId);
    }

    @Override
    public List<GoodsRankVo> getGoodsRank(JoeoneRequest joeoneRequest) {
        String period = joeoneRequest.getPeriod();
        String startDate = "99999999";
        String endDate = period;

        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");
        LocalDate periodDate = LocalDate.parse(period, formatter);

        switch (joeoneRequest.getDateType()) {
            case "日":
                startDate = period;
                break;
            case "周":
                startDate = queryWeekStart(period);
                break;
            case "月":
                startDate = periodDate.withDayOfMonth(1).format(formatter);
                break;
            case "年":
                startDate = periodDate.withDayOfYear(1).format(formatter);
                break;
        }

        List<GoodsRankVo> goodsRank = performanceOverviewMapper.getGoodsRank(joeoneRequest, startDate, endDate);

        if (StringUtils.isNotEmpty(joeoneRequest.getKey())) {
            String str = joeoneRequest.getKey().toUpperCase();
            goodsRank = goodsRank.stream()
                    .filter(goodsRankVo ->
                            (goodsRankVo.getCode().indexOf(str) > -1 || goodsRankVo.getName().indexOf(str) > -1))
                    .collect(Collectors.toList());
        }


        // 获取商品编码列表
        List<String> goodsCodes = goodsRank.stream()
                .map(GoodsRankVo::getCode)
                .collect(Collectors.toList());

        List<JSONObject> imageList = performanceOverviewMapper.getGoodsImages(goodsCodes);
        // 将结果集按商品编码分组
        Map<String, List<String>> imageMap = imageList.stream()
                .collect(Collectors.groupingBy(json -> json.getString("GOODS_CODE"),
                        Collectors.mapping(json -> json.getString("GOODS_IMG"), Collectors.toList())));

        // 遍历原始的GoodsRankVo列表，查找对应的图片并添加到img集合中
        for (GoodsRankVo temp : goodsRank) {
            String goodsCode = temp.getCode();
            List<String> images = imageMap.get(goodsCode);
            temp.setImg(images);
        }

        return goodsRank;
    }

    @Override
    public List<String> queryType() {
        return performanceOverviewMapper.queryType();
    }

    @Override
    public List<String> queryQDYT() {
        return performanceOverviewMapper.queryQDYT();
    }

    public String queryWeekStart(String period) {
        return performanceOverviewMapper.queryWeekStart(period);
    }

    public String getTq(String period) {
        return String.valueOf(Integer.valueOf(period) - 10000);
    }

    public String getHbDate(String period, String dateType) {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");
        LocalDate now = LocalDate.parse(period, formatter);
        if ("周".equals(dateType)) {
            return now.minusDays(1).format(formatter);
        } else if ("周".equals(dateType)) {
            return now.minusDays(7).format(formatter);
        } else if ("月".equals(dateType)) {
            return now.minusMonths(1).format(formatter);
        } else if ("年".equals(dateType)) {
            return now.minusYears(1).format(formatter);
        }
        return "";
    }
}
